package crontab

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"
	"snake/app/service/crontab"
	"snake/library/base"
	"strings"
)

type Action struct {
	base.BaseRouter
}

// path: /get/{id}
func (action *Action) Get(r *ghttp.Request) {
	id := r.GetInt64("id")
	model, err := crontab.GetById(id)
	if err != nil {
		base.Fail(r, err.Error())
	}
	// hostIds := string.Split(model.Hosts,",")
	// hostMap := make(map[string]int)
	// for index, value := range hostIds{
	// 	k := string(index)
	// 	hostMap[k] = int(v)
	// }
	// model.Hosts, err = json.Marshal(hostMap)
	// if err != nil {
	// 	glog.Error(err)
	// }
	base.Succ(r, model)
}

// path: /delete/{id}
func (action *Action) Delete(r *ghttp.Request) {
	id := r.GetInt64("id")
	_, err := crontab.Delete(id, base.GetUser(r).Id)
	if err != nil {
		base.Fail(r, err.Error())
	}
	base.Succ(r, "")
}

// path: /save
func (action *Action) Save(r *ghttp.Request) {
	rmap := r.GetMap()
	cronEntity := make(map[string]interface{},1)
	hosts := ""
	for _,v := range rmap["hosts"].(map[string]interface{}) {
		hosts += gconv.String(v) + ","
	}
	hosts = strings.TrimRight(hosts, ",")
	cronEntity["hosts"] = hosts
	cronEntity["id"] = rmap["id"]
	value, ok := rmap["scriptId"]
	if ok {
		cronEntity["scriptId"] = value
	} else {
		cronEntity["scriptId"] = 0
	}
	cronEntity["spec"] = rmap["spec"]
	cronEntity["name"] = rmap["name"]
	cronEntity["remark"] = rmap["remark"]
	glog.Info("cronEntity:", cronEntity)
	
	request := new(crontab.Request)
	err := gconv.Struct(cronEntity, request)
	if err != nil {
		glog.Error("save struct error", err)
		base.Error(r, "save error")
	}
	request.UserId = base.GetUser(r).Id
	_, err = crontab.Save(request)
	if err != nil {
		base.Fail(r, "保存失败")
	}
	base.Succ(r, "")
}

// path: /list
func (action *Action) List(r *ghttp.Request) {
	form := base.NewForm(r.GetMap())
	list, err := crontab.List(&form)
	if err != nil {
		glog.Error("page error", err)
		base.Error(r, err.Error())
	}
	base.Succ(r, list)
}

// path: /page
func (action *Action) Page(r *ghttp.Request) {
	form := base.NewForm(r.GetMap())
	page, err := crontab.Page(&form)
	if err != nil {
		glog.Error("page error", err)
		base.Error(r, err.Error())
	}
	base.Succ(r,
		g.Map{
			"page":    form.Page,
			"rows":    page,
			"total":   form.TotalPage,
			"records": form.TotalSize,
		})
}

// path: /jqgrid
func (action *Action) Jqgrid(r *ghttp.Request) {
	form := base.NewForm(r.GetMap())
	page, err := crontab.Page(&form)
	if err != nil {
		glog.Error("jqgrid error", err)
		base.Error(r, err.Error())
	}

	r.Response.WriteJson(g.Map{
		"page":    form.Page,
		"rows":    page,
		"total":   form.TotalPage,
		"records": form.TotalSize,
	})
}

